#include "msgparserc.h"
#include <QDebug>
#include "mdefines.h"

using namespace ns_yht;

Q_GLOBAL_STATIC(MsgParserC, g_msgParserC)

MsgParserC::MsgParserC()
{
}

MsgParserC::~MsgParserC()
{
}

MsgParserC *MsgParserC::instance()
{
    return g_msgParserC;
}

void MsgParserC::processBuffer(const QByteArray &buffer)
{
    // QByteArrayList bufferList;
    // bufferList = buffer.split(buffer.contains(LF) ? LF : CR1);

    // int n = bufferList.count();

    // if (n == 0)
    //     return;
    // else if (n == 1)
    //     m_lastMsg.append(buffer.trimmed());
    // else
    // {
    //     QByteArray s = m_lastMsg + bufferList.first();
    //     parse(s.trimmed());

    //     for (int i = 1; i < n - 1; i++)
    //     {
    //         parse(bufferList.at(i).trimmed());
    //     }
    //     m_lastMsg = bufferList.last().trimmed();
    // }

    parse(buffer);
}

void MsgParserC::parse(const QByteArray &msg)
{
    QByteArrayList slist = msg.split('#');
    // qInfo() << "parse---" << slist;
    foreach (auto &s, slist)
    {
        if (s == "")
            continue;
        if (s.left(3) == "MSG")
            processMsg(s);
        if (s.left(4) == "TIME")
            processTime(s);
        else if (s.left(7) == "OWNSHIP")
            processOwnShip(s);
        else if (s.left(7) == "VIDEOAI")
            processAI(s);
    }
}

void MsgParserC::processOwnShip(const QByteArray &sentence)
{
    QByteArrayList slist = sentence.split(',');
    // qInfo() << "processOwnShip" << slist << slist.count();
    if (slist.count() < 12)
        return;

    if (slist.at(1) != "" && slist.at(2) != "")
    {
        double lon = slist.at(1).toDouble();
        double lat = slist.at(2).toDouble();
        double rot = slist.at(3).toDouble();
        double sog = slist.at(4).toDouble();
        double cog = slist.at(5).toDouble();
        double trueheading = slist.at(6).toDouble();

        double pitch = slist.at(9).toDouble();
        double roll = slist.at(10).toDouble();

        emit ownShipReceived(lat, lon, rot, sog, cog, trueheading, roll, pitch);
    }
    if (slist.at(7) != "" && slist.at(8) != "")
    {
        double windangle = slist.at(7).toDouble();
        double windspeed = slist.at(8).toDouble();
        emit windReceived(windangle, windspeed);
    }
    if (slist.at(11) != "")
    {
        int range = slist.at(11).toInt();
        emit radarRangeChanged(range);
    }
}

void MsgParserC::processTime(const QByteArray &sentence)
{
    QByteArrayList slist = sentence.split(',');
    if (slist.count() != 2)
        return;
    emit timeChanged(slist.last().toLongLong());
}

void MsgParserC::processRadarRange(const QByteArray &sentence)
{
    //    emit radarRangeChanged();
}

void MsgParserC::processAI(const QByteArray &sentence) {}

void MsgParserC::processMsg(const QByteArray &sentence)
{
    QByteArrayList slist = sentence.split(',');
    if (slist.count() < 2)
        return;
    emit newMsg(slist.last());
}